<script setup>
import { ref, onMounted, watch } from "vue";
import {sleep} from "openai/core";
import PlayButtonSvg from "@/svg/PlayButtonSvg.vue";
import PauseButtonSvg from "@/svg/PauseButtonSvg.vue";
import VolumeMuteSvg from "@/svg/VolumeMuteSvg.vue";
import VolumeButtonSvg from "@/svg/VolumeButtonSvg.vue";
import {lrcState} from "@/store/songStore";
const props = defineProps({
  audioUrl: String,        //试听的链接
  isPauseTtsAudio: Boolean     //是否暂停播放试听
});
const audioIsPlay = ref(true); //音频是否在播放
const audioStart = ref("0:00");
const durationTime = ref("0:00"); //音频的总时长，显示的时间格式
const duration = ref(0); //音频的总时长
const audioVolume = ref(80); //音量的默认值是0.8
const audioHuds = ref(false); //是否显示音量slider
const audioRef = ref(null);
const currentProgress = ref(0);


watch(() => props.isPauseTtsAudio, (newVal, oldVal) => {
  if (newVal) {
    // 如果 isPauseTtsAudio 为 true，试听暂停
    handleCloseMusic();
  }
});
function handleCloseMusic() {
  audioRef.value.pause();
  audioIsPlay.value = true;
}
onMounted(() => {
  calculateDuration();
});
// 获取音频时长
function calculateDuration() {
  var myVid = audioRef.value;
  myVid.loop = false;
  myVid.src = props.audioUrl;
  // 监听音频播放完毕
  myVid.addEventListener(
      "ended",
      function () {
        audioIsPlay.value = true;
        currentProgress.value = 0;
      },
      false
  );
  if (myVid != null) {
    myVid.oncanplay = function () {
      duration.value = myVid.duration; // 计算音频时长
      durationTime.value = transTime(myVid.duration); //换算成时间格式
    };
    myVid.volume = 0.8; // 设置默认音量50%
    // 进入页面默认开始播放
    // audioRef.value.play();
    // audioIsPlay.value = false;
  }
}
// 音频播放时间换算
function transTime(duration) {
  const minutes = Math.floor(duration / 60);
  const seconds = Math.floor(duration % 60);
  const formattedMinutes = String(minutes).padStart(2, "0"); //padStart(2,"0") 使用0填充使字符串长度达到2
  const formattedSeconds = String(seconds).padStart(2, "0");
  return `${formattedMinutes}:${formattedSeconds}`;
}
// 播放暂停控制
function playAudio() {
  if (audioRef.value.paused) {
    audioRef.value.play();
    audioIsPlay.value = false;
  } else {
    audioRef.value.pause();
    audioIsPlay.value = true;
  }
}
// 根据当前播放时间，实时更新进度条
function updateProgress(e) {
  var value = e.target.currentTime / e.target.duration;
  if (audioRef.value.play) {
    currentProgress.value = value * 100;
    audioStart.value = transTime(audioRef.value.currentTime);
  }

  console.log("**timeChange，findIndex")
  let cur = ref(audioRef.value.currentTime)
  lrcState.value.currentIndex=findIndex(cur.value)
  console.log(lrcState.value.currentIndex)

}



function findIndex(curTime){
  console.log(JSON.stringify(curTime))
  if(JSON.stringify(curTime)==="0")
    return 0
  // console.log(audioRef.value.currentTime)
  for (let i =0; i < lrcState.value.lrcList.length; i++) {
    if (curTime < lrcState.value.lrcList[i+1]?.time && curTime > lrcState.value.lrcList[i]?.time){
      // console.log(lrcState.value.lrcList[i - 1].text ? i - 1 : i - 2) ;
      return i
    }
  }
  // 找遍了没有找到（说明播放到歌词的最后一句）
  return (lrcState.value.lrcList.length - 1);
}



//调整播放进度
const handleProgressChange = (val) => {
  console.log(val);
  if (!val) {
    return;
  }
  let currentTime = duration.value * (val / 100);
  // 更新音频的当前播放时间
  audioRef.value.currentTime = currentTime;
};
//调整音量
const handleAudioVolume = (val) => {
  audioRef.value.volume = val / 100;
};
</script>


<template>
  <div class="flex items-center justify-start ">
    <audio
        @timeupdate="updateProgress"
        controls
        ref="audioRef"
        style="display: none"
    >
      <source :src="audioUrl" type="audio/mpeg" />
      您的浏览器不支持音频播放
    </audio>
    <div class=" h-10 flex justify-center items-center rounded-2xl bg-gray-1 gap-3 px-5">
      <pause-button-svg
          class=" text-#51596d hover:text-yellow w-6 h-6 "
                       v-if="!audioIsPlay"
                       @click="playAudio"
      >
      </pause-button-svg>
      <play-button-svg
          v-if="audioIsPlay"
          @click="playAudio"
          class=" text-#51596d hover:text-yellow w-6 h-6"
      >
      </play-button-svg>
      <div class="w-100">
        <el-slider
            class="slider_box "
            v-model="currentProgress"
            :show-tooltip="false"
            @input="handleProgressChange"
        />

      </div>
      <div class="text-gray-5 text-3 w-25">
        <span class="">{{ audioStart }}</span>
        &nbsp;/&nbsp;
        <span class="">{{ durationTime }}</span>
      </div>
      <div class="volume">
        <div class="volume_progress" v-show="audioHuds">
          <el-slider
              vertical
              height="100px"
              class="volume_bar flex justify-center items-center bg-white border-3 border-yellow-2 rounded-xl"
              v-model="audioVolume"
              :show-tooltip="false"
              @change="handleAudioVolume"
          />
        </div>
        <volume-mute-svg
            class=" w-5.5 h-5.5 text-#51596d hover:text-yellow "
            v-if="audioVolume <= 0"
            @click.stop="audioHuds = !audioHuds"
        ></volume-mute-svg>
        <volume-button-svg
            class="w-5.5 h-5.5 text-#51596d hover:text-yellow "
            v-if="audioVolume > 0"
            @click.stop="audioHuds = !audioHuds"
        >
        </volume-button-svg>
      </div>

    </div>
  </div>
</template>



<style lang="scss" scoped>
.audio_right {
  height: 40px;
  padding: 0 10px;
  box-sizing: border-box;
  position: relative;
  .slider_box {
    height: 4px;
    border-radius: 5px;
    background-color: #f1f1f1;
    flex: 1;
    margin: 0 8px 4px;
  }
  .audio_icon {
    width: 20px;
    height: 20px;
    margin-bottom: 4px;
    cursor: pointer;
  }
  .audio_time {
    color: #f1f1f1;
    overflow: hidden;
    font-size: 12px;
    position: absolute;
    bottom: 3px;
    left: 80px;
    .audio_total {
      float: right;
    }
    .audio_current {
      float: left;
    }
  }
}
.volume {
  position: relative;
  .volume_progress {
    width: 32px;
    height: 140px;
    position: absolute;
    top: -142px;
    right: -4px;
  }
  .volume_bar {
    background: #fff;
  }
  .volume_icon {
    width: 24px;
    height: 24px;
    cursor: pointer;

  }
}
</style>
<style lang="scss">
.el-slider__button-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;

}
.slider_box,
.volume_bar {
  .el-slider__button {
    width: 8px;
    height: 8px;
    border:none;
    background-color: #facc15;
  }
  .el-slider__bar {
    background: #ffebb1;
  }
}
.slider_box {
  .el-slider__button-wrapper {
    width: 8px;
  }
}
.volume_bar {
  .el-slider__runway {
    margin: 0 14px !important;
  }
}
</style>

